<?php

declare(strict_types=1);

namespace Yansongda\Pay\Plugin\Sbpay;

use Closure;
use GuzzleHttp\Psr7\Utils;
use Yansongda\Pay\Contract\PluginInterface;
use Yansongda\Pay\Exception\ContainerException;
use Yansongda\Pay\Exception\InvalidConfigException;
use Yansongda\Pay\Exception\ServiceNotFoundException;
use Yansongda\Pay\Logger;
use Yansongda\Pay\Rocket;
//use Yansongda\Pay\Traits\GetSbpayCerts;
use Yansongda\Supports\Collection;

use function Yansongda\Pay\get_sbpay_config;

class RadarSignPlugin implements PluginInterface
{
//    use GetSbpayCerts;

    /**
     * @throws ContainerException
     * @throws ServiceNotFoundException
     * @throws InvalidConfigException
     */
    public function assembly(Rocket $rocket, Closure $next): Rocket
    {
        Logger::debug('[sbpay][PreparePlugin] 插件开始装载', ['rocket' => $rocket]);

        $this->sign($rocket);

        $this->reRadar($rocket);

        Logger::info('[sbpay][PreparePlugin] 插件装载完毕', ['rocket' => $rocket]);

        return $next($rocket);
    }

    /**
     * @throws ContainerException
     * @throws InvalidConfigException
     * @throws ServiceNotFoundException
     */
    protected function sign(Rocket $rocket): void
    {
        $payload = $rocket->getPayload()->filter(fn ($v, $k) => 'sps_hashcode' != $k);
        $config = $this->getConfig($rocket->getParams());

        $rocket->mergePayload([
            'sps_hashcode' => $this->getSignature($config['hash_key'] ?? '', $payload),
        ]);
    }

    protected function reRadar(Rocket $rocket): void
    {
        $body = $this->getBody($rocket->getPayload());
        $radar = $rocket->getRadar();

        if (!empty($body) && !empty($radar)) {
            $radar = $radar->withBody(Utils::streamFor($body));

            $rocket->setRadar($radar);
        }
    }

    /**
     * @throws ContainerException
     * @throws InvalidConfigException
     * @throws ServiceNotFoundException
     */
    protected function getConfig(array $params): array
    {
        $config = get_sbpay_config($params);

//        if (empty($config['certs']['pkey'])) {
//            $this->getCertId($params['_config'] ?? 'default', $config);
//
//            $config = get_sbpay_config($params);
//        }

        return $config;
    }

    protected function getSignature(string $pkey, Collection $payload): string
    {

        // Concatenate the data and append the hash key.
        $checksum_string = implode($payload->toArray());
        $checksum_string .= $pkey;
//        print_r($payload->toArray());
//        exit();
        // We need to convert the encoding to allow for japanese characters.
        $checksum_string = mb_convert_encoding($checksum_string, 'UTF-8', 'SJIS');

        // Calculate the hash code.
        return strtoupper(sha1($checksum_string));
    }

    protected function getBody(Collection $payload): string
    {
        return $payload->query();
    }
}
